package com.example.demo.controller;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

@Controller
@CrossOrigin
public class UploadController {
    @ResponseBody
    @RequestMapping("/upload1")
    public Map<String,Object> upload1(MultipartFile file){
        File path = new File("D:/tupian");
        if (!path.exists()){
            path.mkdir();
        }
        File newFile = new File(path,getFileName(file));
        try {
            //上传过程
            file.transferTo(newFile);
        } catch (IOException e) {
            e.printStackTrace();
        }
        Map<String,Object> map =new HashMap<>();
        map.put("res",newFile.getAbsolutePath());
        return map;
    }
    //封装新的文件名，放到服务器上
    public String getFileName(MultipartFile file){
        UUID uuid = UUID.randomUUID();
        String originalFilename = file.getOriginalFilename();
        String prefix = originalFilename.substring(originalFilename.lastIndexOf(".")+1);
        return uuid.toString()+"."+prefix;
    }
}
